//
//  XZLotteryController.m
//  生活小助手
//
//  Created by lixiangzhou on 14-8-7.
//  Copyright (c) 2014年 lxz. All rights reserved.
//

#define padding 20
#define leftH 30
#define rightH 30
#define rightX  120
#define rightW 175
#define leftW 90
#define SkyBlueColor DColor(0,122,255)
/**通知**/
#define LottoryTypeViewOnClickNotification @"LottoryTypeViewOnClickNotification"

#import "XZLotteryController.h"
#import "XZLotteryTypeView.h"
#import "AFNetworking.h"
#import "MJExtension.h"
#import "XZLotteryType.h"
#import "XZLottery.h"
#import "XZLotteryCell.h"
#import "XZFunctionKey.h"
#import "XZLotteryHeaderView.h"
#import "MBProgressHUD+MJ.h"

@interface XZLotteryController ()<UITableViewDelegate,UITableViewDataSource>
@property (weak,nonatomic) UIButton *loyOpenDateBtn;
@property (assign,nonatomic,getter = isShowDatePicker) BOOL showDatePicker;

@property (weak,nonatomic) UIButton *loyTypeBtn;

@property (weak,nonatomic) UITextField *loyIDTextField;

@property (strong,nonatomic) UIDatePicker *datePicker;

@property (strong,nonatomic) XZLotteryTypeView *typeView;

@property (weak,nonatomic) XZLotteryHeaderView *headerView;

@property (weak,nonatomic) UITableView *tableView;
/**tableView的显示**/
@property (strong,nonatomic) NSArray *lotterys;

@property (assign,nonatomic) NSInteger lottoryId;

@property (assign,nonatomic) NSInteger segmentSelectIndex;

@property (weak,nonatomic) UISegmentedControl *segment;

@property (weak,nonatomic) UILabel *loyOpenDateLable;
@end

@implementation XZLotteryController

- (NSArray *)lotterys
{
    if (!_lotterys) {
        _lotterys = [NSMutableArray array];
    }
    return _lotterys;
}

- (UIDatePicker *)datePicker
{
    if (!_datePicker) {
        _datePicker = [[UIDatePicker alloc]init];
        _datePicker.backgroundColor = [UIColor whiteColor];
        _datePicker.datePickerMode = UIDatePickerModeDate;
        NSLocale *chinaLocal = [[NSLocale alloc]initWithLocaleIdentifier:@"zh-Hans"];
        _datePicker.locale = chinaLocal;
        _datePicker.x = 0;
        _datePicker.y = CGRectGetMaxY(self.loyOpenDateBtn.frame) + padding;
        [self.view addSubview:_datePicker];
        _datePicker.hidden = YES;
        [_datePicker addTarget:self action:@selector(datePicker:) forControlEvents:UIControlEventValueChanged];
    }
    return _datePicker;
}
- (XZLotteryTypeView *)typeView
{
    if (!_typeView) {
        _typeView = [[XZLotteryTypeView alloc]init];
        
        XZLotteryType *type = [[XZLotteryType alloc]init];
        type.lottery = @"足球";
        
        XZLotteryType *type2 = [[XZLotteryType alloc]init];
        type2.lottery = @"福彩3d";
        
        XZLotteryType *type3= [[XZLotteryType alloc]init];
        type3.lottery = @"大乐透";
        _typeView.typeArry = @[type,type2,type3];
        _typeView.x = self.loyTypeBtn.x;
        _typeView.y = CGRectGetMaxY(self.loyTypeBtn.frame);
        _typeView.width = self.loyTypeBtn.width;
        [self.view addSubview:_typeView];
        _typeView.hidden = YES;
    }
    return _typeView;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        NSLog(@"=-=initWithNibName");
        self.title = @"彩票查询";
        self.view.backgroundColor  =  [UIColor whiteColor];
        
        /**发送请求获取彩票的类型**/
        AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
        //http://v.juhe.cn/lottery/lolist.php?key=xxxxx
        
        NSString *url =[NSString stringWithFormat:@"http://v.juhe.cn/lottery/lolist.php?key=%@",@"3397750e43bc88b7d5d3b8154935bbb3"];
        
        [mgr GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, NSDictionary  *responseObject) {
            NSArray *loyTypeArray = responseObject[@"result"];
            NSArray *loyTypes = [XZLotteryType objectArrayWithKeyValuesArray:loyTypeArray];
            NSLog(@"彩票类星==%@",loyTypeArray);
            self.typeView.typeArry = loyTypes;
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"%@",error);
        }];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    /**监听通知**/
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(lottoryTypeViewOnClick:) name:LottoryTypeViewOnClickNotification object:nil];
    
    /**segent**/
    UISegmentedControl *segment = [[UISegmentedControl alloc]initWithItems:@[@"彩票查询",@"历史查询"]];
    segment.x = 0;
    segment.y = 64;
    segment.width = kScreenWidth;
    segment.selectedSegmentIndex = 0;
    [segment addTarget:self action:@selector(segmentSelect:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:segment];
    self.segment = segment;
    
    /**彩票种类**/
    UILabel *loyTypeLabel = [[UILabel alloc]init];
    loyTypeLabel.text = @"彩票种类:";
    loyTypeLabel.frame = CGRectMake(padding, CGRectGetMaxY(segment.frame), leftW, leftH);
    [self.view addSubview:loyTypeLabel];
    
    UIButton *loyTypeBtn = [[UIButton alloc]init];
    loyTypeBtn.frame = CGRectMake(rightX, loyTypeLabel.y, rightW , rightH);
    [loyTypeBtn setTitle:@"请选择彩票种类" forState:UIControlStateNormal];
    [loyTypeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [loyTypeBtn addTarget:self action:@selector(typeSelect:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:loyTypeBtn];
    self.loyTypeBtn = loyTypeBtn;
    
    /**开奖日期**/
    UILabel *loyOpenDateLable = [[UILabel alloc]init];
    loyOpenDateLable.text = @"开奖日期:";
    loyOpenDateLable.frame = CGRectMake(padding, CGRectGetMaxY(loyTypeBtn.frame) + padding, leftW, leftH);
    [self.view addSubview:loyOpenDateLable];
    self.loyOpenDateLable = loyOpenDateLable;
    
    UIButton *loyOpenDateBtn = [[UIButton alloc]init];
    loyOpenDateBtn.frame = CGRectMake(rightX, loyOpenDateLable.y, rightW, rightH);
    [loyOpenDateBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [loyOpenDateBtn addTarget:self action:@selector(dateSelect:) forControlEvents:UIControlEventTouchUpInside];
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"yyyy-MM-dd";
    NSString *today = [formatter stringFromDate:date];
    [loyOpenDateBtn setTitle:today forState:UIControlStateNormal];
    [self.view addSubview:loyOpenDateBtn];
    self.loyOpenDateBtn = loyOpenDateBtn;
    
    
    XZLotteryHeaderView *headerView = [[XZLotteryHeaderView alloc]init];
    [self.view addSubview:headerView];
    headerView.frame = CGRectMake(0, CGRectGetMaxY(loyOpenDateBtn.frame) + padding, kScreenWidth, leftH);
    headerView.hidden = YES;
    self.headerView = headerView;
    /**显示查询结果**/
    UITableView *tableView = [[UITableView alloc]init];
    tableView.frame = CGRectMake(0, CGRectGetMaxY(headerView.frame), kScreenWidth, 240);
    [self.view addSubview:tableView];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.hidden = YES;
    self.tableView = tableView;
    
    /**查询按钮**/
    UIButton *searchBtn = [[UIButton alloc]init];
    searchBtn.frame = CGRectMake(0,kScreenHeight - 44, kScreenWidth, 44);
    searchBtn.backgroundColor = [UIColor orangeColor];
    [searchBtn setTitle:@"查询" forState:UIControlStateNormal];
    [searchBtn setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
    [searchBtn addTarget:self action:@selector(searchBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:searchBtn];
}
/**
 * 切换segment
 */
- (void)segmentSelect:(UISegmentedControl *)segment
{
    NSLog(@"selectedSegmentIndex = %d",segment.selectedSegmentIndex);
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    
    if (segment.selectedSegmentIndex == 0)
    {
        formatter.dateFormat = @"yyyy-MM-dd";
         self.loyOpenDateLable.text = @"开奖日期:";
    }
    else
    {
        formatter.dateFormat = @"yyyy";
         self.loyOpenDateLable.text = @"历史年份:";
    }
    NSString *dateStr = [formatter stringFromDate:date];
    
    [self.loyOpenDateBtn setTitle:dateStr forState:UIControlStateNormal];
    
    
}

/**点击按钮查询彩票信息**/
- (void)searchBtnClick:(UIButton *)btn
{
    /**因此可见的控件**/
     self.datePicker.hidden = YES;
    
    /**先验证日期是否正确**/
    NSDate *today = [NSDate date];
    if ([self.datePicker.date compare:today] ==  NSOrderedDescending) {
        [MBProgressHUD showError:@"日期不对"];
        return;
    }
    //    /**根据segment来决定发送什么请求**/
     AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];

    if (self.segment.selectedSegmentIndex == 1) {
        
        if ([self.loyOpenDateBtn.currentTitle intValue] < 2012) {
            UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"警告" message:@"只能查询2012及以后的数据" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alter show];
            return;
        }
        NSString *url = [NSString stringWithFormat:@"http://v.juhe.cn/lottery/history?key=%@&lotteryid=%d&year=%@",[XZFunctionKey lotteryKey],self.lottoryId,self.loyOpenDateBtn.currentTitle];
        [MBProgressHUD showMessage:@"正在拼命查询..."];
        [mgr GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject) {
            
            [MBProgressHUD hideHUD];
            NSArray *result = responseObject[@"result"];
            
            if (result.count == 0) {
                [MBProgressHUD showError:@"没查询到相关数据"];
                return ;
            }
            
            NSArray *lotterys = [XZLottery objectArrayWithKeyValuesArray:result];
            
            self.lotterys = lotterys;
            self.tableView.hidden = NO;
            self.headerView.hidden = NO;
            [self.tableView reloadData];

        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            
            [MBProgressHUD hideHUD];
        }];
    }
    else
    {
        NSString *url = [NSString stringWithFormat:@"http://v.juhe.cn/lottery/query?key=%@&lotteryid=%d&date=%@",[XZFunctionKey lotteryKey],self.lottoryId,self.loyOpenDateBtn.currentTitle];
        [mgr GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            [MBProgressHUD hideHUD];
            NSArray *result = responseObject[@"result"];
            if (result.count == 0) {
                [MBProgressHUD showError:@"没查询到相关数据"];
                return ;
            }
            NSArray *lotterys = [XZLottery objectArrayWithKeyValuesArray:result];
            self.lotterys = lotterys;
            self.tableView.hidden = NO;
            self.headerView.hidden = NO;
            [self.tableView reloadData];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [MBProgressHUD hideHUD];
        }];

    }
}

/*!
 *  选择彩票类型
 *
 *  @param btn
 */
- (void)typeSelect:(UIButton *)btn
{
    self.typeView.hidden = !self.typeView.hidden;
}

/*!
 *  选择开奖日期按钮事件
 *
 *  @param btn
 */
- (void)dateSelect:(UIButton *)btn
{
    [self.view endEditing:YES];
    self.datePicker.hidden = !self.datePicker.hidden;
}

/*!
 * 时间件选择控件方法
 *
 *  @param datePicker
 */
-  (void)datePicker:(UIDatePicker *)datePicker
{
    NSLog(@"%@",datePicker.date);
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    if (self.segment.selectedSegmentIndex == 0) {
        formatter.dateFormat = @"yyyy-MM-dd";
        
    }
    else
    {
        formatter.dateFormat = @"yyyy";
    }
    
    NSString *date = [formatter stringFromDate:datePicker.date];
    [self.loyOpenDateBtn setTitle:date forState:UIControlStateNormal];
}

/*!
 *  通知监听方法
 */
-  (void)lottoryTypeViewOnClick:(NSNotification *)notification
{
    UIButton *loyTypeBtn = notification.userInfo[@"loyType"];
    [self.loyTypeBtn setTitle:loyTypeBtn.currentTitle forState:UIControlStateNormal];
    
    self.lottoryId = loyTypeBtn.tag;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

#pragma mark - tableView的代理和数据源
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.lotterys.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"lottery";
    XZLotteryCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (!cell) {
        cell = [[XZLotteryCell alloc]init];
        
    }
    cell.lottery = self.lotterys[indexPath.row];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}
@end
